﻿using System;
using System.ServiceModel.DomainServices.Client;
using RIBA.Web;

namespace RIBA.Helper
{
	public static class OperationBaseErrorHandler
	{
		public static string GetErrMsg(OperationBase operation)
		{
			var errMsg = "";

			if (operation.IsCanceled)
				errMsg = TextRes.Cancel;

			else if (operation.HasError)
			{
				if (operation.Error is DomainOperationException)
				{
					if (operation.Error.InnerException is TimeoutException)
						errMsg = TextRes.Timeout;
					else
					{
						var domainOperationException = operation.Error as DomainOperationException;
						if (domainOperationException.Status == OperationErrorStatus.Unauthorized)
						{
							errMsg = TextRes.RequiresAuthentication;
							//if (WebContext.Current != null)
							//{
							//  WebContext.Current.Authentication.Logout(false);
							//  errMsg = TextRes.RequiresAuthentication;
							//}
							//else
							//  errMsg = "WebContext.Current == null";
						}
						else
						{
							if (operation.Error.Message.Contains("MaxReceivedMessageSize"))
								errMsg = TextRes.MaxReceivedMessageSize;
							else
								errMsg = operation.Error.Message;
						}
					}
				}
				else
					errMsg = operation.Error.Message;

				operation.MarkErrorAsHandled();
			}

			return errMsg;
		}
	}
}
